/**
 * static:
 * 静态文件请求处理主模块
 *
 * User: ZhangXiao
 * Date: 14-4-23
 * Time: 下午9:50
 * File: sys/static.js
 */

var fs = require("fs");
var path = require("path");
var mime = require("./mime").mime;
var util = require("util");
var tools = require("./tools");
var cache = require("./cache").cache();

var _options = {};
var _handlers = {};
var _public = ".";
var _approot = ".";


function sendFile(response, filePath, fileContents) {
    response.writeHead(200, {
        "Content-Type": mime.lookup(path.extname(filePath))
    });
    response.write(fileContents, "binary");
    response.end();
}

//主处理方法
function staticHandler(path, request, response, options) {

    _options = tools.copyObject(options);
    _handlers = _options.handlers;
    _approot = _options.approot;
    _public = path.resolve(_options.approot, _options.app.client);

    util.log("Static request url is:" + request.url + " and pathname is:" + pathname);

    //逻辑处理
    var co = cache.get(pathname);
    if (co) {
        sendFile(response, pathname, co.data);
    } else {
        //静态文件物理路径
        pathname = _public + pathname;
        fs.exists(pathname, function (exits) {
            if (exits) {
                fs.readFile(pathname, "binary",
                    function (err, data) {
                        if (err) {
                            _handlers["handler_404"](request, response, _options);
                        } else {
                            cache.add(pathname, data);
                            sendFile(response, pathname, data);
                        }
                    }
                );
            } else {
                _handlers["handler_404"](request, response, _options);
            }
        });
    }
}

exports.static = staticHandler;
